﻿// The MIT License (MIT)
// Copyright (c) 2014 Grégory Ghez
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace JenkinsController.ViewModel
{
    using System;
    using System.Net;
    using System.Text;
    using System.Windows;
    using System.Windows.Threading;
    using Framework;
    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Messaging;
    using Jenkins.Domain;
    using Model;

    public class LogsViewModel : ViewModelBase, IDisposable
    {
        private readonly IDataService dataService;
        private JenkinsBuild build;
        private string filteredLogText;
        private bool isAutoRefreshed;
        private bool isDisposed;
        private string logText;
        private string quickFilter;
        private DispatcherTimer timer;
        private bool wasBuilding = true;

        public LogsViewModel(IMessenger messenger, IDataService dataService)
            : base(messenger)
        {
            this.dataService = dataService;

            this.isAutoRefreshed = true;

            this.TrySetAutoRefreshTimer();
        }

        public bool IsAutoRefreshed
        {
            get { return this.isAutoRefreshed; }
            set
            {
                if (this.isAutoRefreshed != value)
                {
                    this.isAutoRefreshed = value;
                    this.TrySetAutoRefreshTimer();

                    this.RaisePropertyChanged(() => this.IsAutoRefreshed);
                }
            }
        }

        public string QuickFilter
        {
            get { return this.quickFilter; }
            set
            {
                if (this.quickFilter != value)
                {
                    this.quickFilter = value;
                    this.FilterLogText();
                    this.RaisePropertyChanged(() => this.QuickFilter);
                }
            }
        }

        public string FilteredLogText
        {
            get { return this.filteredLogText; }
            set
            {
                if (this.filteredLogText != value)
                {
                    this.filteredLogText = value;
                    this.RaisePropertyChanged(() => this.FilteredLogText);
                }
            }
        }

        public string LogText
        {
            get { return this.logText; }
            set
            {
                if (this.logText != value)
                {
                    this.logText = value;
                    this.FilterLogText();
                    this.MessengerInstance.Send(new LogsUpdatedMessage { Build = this.Build });
                    this.RaisePropertyChanged(() => this.LogText);
                }
            }
        }

        public JenkinsBuild Build
        {
            get { return this.build; }
            set
            {
                this.build = value;
                if (this.build != null)
                {
                    this.RefreshAsync();
                }

                this.RaisePropertyChanged(() => this.Build);
            }
        }

        public void Dispose()
        {
            if (!this.isDisposed)
            {
                this.Dispose(true);
                GC.SuppressFinalize(this);

                this.isDisposed = true;
            }
        }

        private void FilterLogText()
        {
            string filteredText = this.LogText;

            if (!string.IsNullOrWhiteSpace(this.QuickFilter) && this.LogText != null && !string.IsNullOrWhiteSpace(this.QuickFilter))
            {
                var builder = new StringBuilder();
                string[] lines = this.LogText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lines)
                {
                    if (line.Contains(this.QuickFilter))
                    {
                        builder.AppendLine(line);
                    }
                }

                filteredText = builder.ToString();
            }

            this.FilteredLogText = filteredText;
        }

        ~LogsViewModel()
        {
            this.Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.timer != null && this.timer.IsEnabled)
                {
                    this.timer.Stop();
                }
            }
        }

        private bool TrySetAutoRefreshTimer()
        {
            if (this.timer == null)
            {
                this.timer = new DispatcherTimer(TimeSpan.FromSeconds(3d), DispatcherPriority.Background, (s, e) => this.RefreshAsync(), Application.Current.Dispatcher);
            }

            if (!this.timer.IsEnabled)
            {
                this.timer.Start();
                return true;
            }

            return false;
        }

        private async void RefreshAsync()
        {
            if (this.Build == null)
            {
                return;
            }

            await this.dataService.UpdateAsync(this.Build);
            if (this.wasBuilding || this.Build.IsBuilding)
            {
                using (var wc = new WebClient())
                {
                    this.LogText = await wc.DownloadStringTaskAsync(this.Build.ConsoleTextUrl);
                }

                wasBuilding = Build.IsBuilding;
            }
        }
    }
}